package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.SysRoleDto;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.entity.SysRoleMenu;
import com.itheima.ydd.mapper.SysRoleMapper;
import com.itheima.ydd.service.ISysRoleMenuService;
import com.itheima.ydd.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@Service
@Slf4j
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
    @Autowired
    private ISysRoleMenuService sysRoleMenuService;

    @Override
    public ResultData getAllData() {
        List<SysRole> list = list();
        return ResultData.ok("查询成功！", list);
    }

    @Override
    public ResultData getList(Integer page, Integer limit, String name) {
        //分页构造器
        Page pageInfo = new Page(page, limit);

        //模糊查询条件
        LambdaQueryWrapper<SysRole> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null, SysRole::getName, name);

        //排序

        //分页查询
        page(pageInfo, lqw);

        //封装对象
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", pageInfo.getRecords());
        map.put("count", pageInfo.getTotal());
        map.put("totalPages", pageInfo.getSize());
        map.put("pageSize", limit);
        map.put("currentPage", pageInfo.getCurrent());
//        map.put("currentPage",)
        //返回
        return ResultData.ok("查询成功", map);
    }

    @Override
    public ResultData add(SysRoleDto sysRoleDto) {
        log.error("id为{}",sysRoleDto.getId());
        sysRoleDto.setCreateDate(LocalDateTime.now());
        sysRoleDto.setUpdateDate(LocalDateTime.now());

        save(sysRoleDto);
        //获取添加后的id
        String id = sysRoleDto.getId();
        List<String> menuids = sysRoleDto.getMenuids();

        for (String menuid : menuids) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(id);
            sysRoleMenu.setMenuId(menuid);
            sysRoleMenuService.save(sysRoleMenu);
        }
        return ResultData.ok("添加成功");
    }
}
